/*
 *************************************************************************
 *西瑞克斯研发管理系统
 *版 本: 1.0   
 *日 期：02/08/2012    
 *作 者： 王浩 QQ：873987060   
 *************************************************************************   
 */
package com.application.function.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.application.function.entity.Function;
import com.application.function.entity.Menu;
import com.application.function.struts.form.FunctionForm;
import com.application.model.entity.Model;
import com.application.role.entity.Role;
import com.manager.BaseDao;
import com.manager.commons.DateUtil;
import com.manager.commons.page.PageBean;

/**
 * 
 * Description:FunctionDAO<br />
 * 
 * Version:V0.1<br />
 * 
 * Author: 左磊 QQ：30575951 <br />
 * 
 * History: <br />
 * 
 * 02/08/2012
 * 
 */
public class FunctionDAO extends BaseDao {
	private static final Logger logger = Logger.getLogger(FunctionDAO.class);

	private Function function;

	public Function getFunction() {
		return this.function;
	}

	public void setFunction(Function function) {
		this.function = function;
	}

	public Integer getAllCountFunction(FunctionForm functionForm) {
		// 储存查询条件的buffer
		StringBuffer buf = new StringBuffer();
		buf.append("select count(*) from Function t ");
		// 查询字符串
		String strSql = getStringBuffer(functionForm, buf).toString();

		return Integer.parseInt(this.getHibernateTemplate().find(strSql).get(0)
				.toString());
	}

	public void deleteFunctions(FunctionForm functionForm) {
		String a = functionForm.getIds().replaceAll(",", "','");
		String hql = " delete from Function where id in  ( '" + a + "')";
		Session session = this.getSession();
		try {
			session.createQuery(hql).executeUpdate();
		} catch (RuntimeException re) {
			logger.error("deleteFunctions failed");
			throw re;
		} finally {
			if (session != null) {
				releaseSession(session);
			}
		}
	}

	public List searchFunction(final FunctionForm functionForm,
			final PageBean pageBean) {
		StringBuffer buf = new StringBuffer();

		// 返回list集合
		List list = null;

		buf.append("from Function t  ");

		// 查询字符串条件
		buf = getStringBuffer(functionForm, buf);

		// 传递查询条件buf值
		pageBean.setStringBuffer(buf);

		// 分页取得字符串集合
		list = getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				List resutlList = new ArrayList();
				try {
					Query query = session.createQuery(pageBean
							.getStringBuffer().toString()
							+ " order by t.createDate Desc ");

					// 设置开始页
					query.setFirstResult(pageBean.getPageSize()
							* (pageBean.getPageIndex() - 1));

					// 设置结束页
					query.setMaxResults(pageBean.getPageSize());

					List teamsList = query.list();
					if (teamsList != null && teamsList.size() > 0) {
						for (int j = 0; j < teamsList.size(); j++) {
							Function function = (Function) teamsList.get(j);
							resutlList.add(function);
						}
					}
					return resutlList;
				} catch (RuntimeException re) {
					logger.error("searchFunction failed");
					throw re;
				} finally {
					if (session != null) {
						releaseSession(session);
					}
				}
			}
		});
		return list;
	}

	public List searchFunction(final FunctionForm functionForm) {
		StringBuffer buf = new StringBuffer();

		// 返回list集合
		List list = null;

		buf.append("from Function t  ");

		// 查询字符串条件
		buf = getStringBuffer(functionForm, buf);
		final String sql = buf.toString();

		// 分页取得字符串集合
		list = getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				List resutlList = new ArrayList();
				try {
					Query query = session.createQuery(sql
							+ " order by t.px asc ");

					List teamsList = query.list();
					if (teamsList != null && teamsList.size() > 0) {
						for (int j = 0; j < teamsList.size(); j++) {
							Function function = (Function) teamsList.get(j);
							resutlList.add(function);
						}
					}

					return resutlList;
				} catch (RuntimeException re) {
					logger.error("searchFunction failed");
					throw re;
				} finally {
					if (session != null) {
						releaseSession(session);
					}
				}
			}
		});

		return list;
	}

	public void deleteFunctionRole(String fid) {
		String hql = " delete from RoleFunction where fid = '" + fid + "'";
		Session session = this.getSession();
		try {
			session.createQuery(hql).executeUpdate();
		} catch (RuntimeException re) {
			logger.error("deleteFunctionRole failed");
			throw re;
		} finally {
			if (session != null) {
				releaseSession(session);
			}
		}
	}

	public List<Role> getFunctionRole(String fid) {
		List<Role> roleTemp = new ArrayList();
		String hql = "from RoleFunction fr,Role r where r.id = fr.rid and fr.fid = '"
				+ fid + "'";
		Session session = this.getSession();
		try {
			List<Object[]> temp = session.createQuery(hql).list();
			if (temp != null && temp.size() > 0) {
				for (int i = 0; i < temp.size(); i++) {
					Object[] obj = temp.get(i);
					Role role = (Role) obj[1];
					roleTemp.add(role);
				}
			}
		} catch (RuntimeException re) {
			logger.error("getUserRole failed");
			throw re;
		} finally {
			if (session != null) {
				releaseSession(session);
			}
		}
		return roleTemp;
	}

	public List<Function> searchFunctionMenu(String mid) {
		// 返回list集合
		List<Function> list = null;
		String hql = "from Function t where 1=1 ";

		// 查询字符串条件
		if (StringUtils.isNotBlank(mid) && !mid.equals("0")) {
			hql = hql + " and t.mid = '" + mid.trim() + "'";
		}
		Session session = this.getSession();
		// 分页取得字符串集合
		try {
			Query query = session.createQuery(hql + " order by t.px asc ");
			list = query.list();
		} catch (RuntimeException re) {
			logger.error("searchFunctionMenu failed");
			throw re;
		} finally {
			if (session != null) {
				releaseSession(session);
			}
		}
		return list;
	}

	public List<Menu> searchFunctionMenu(String mid, String uid) {
		// 返回list集合
		List<Menu> list = new ArrayList<Menu>();
		String sql = "";
		if ("2012021900215738395".equals(uid)) {
			sql = "select * from ("
					+ "select id,name,'m' as lx,'#' as url,fid,px from model where  fid = '"
					+ mid
					+ "' union all "
					+ "select id,name,'f' as lx,url,mid as fid,px from function where  mid = '"
					+ mid + "' )as a  order by px asc ";
		} else {
			sql = "select * from ("
					+ "select id,name,'m' as lx,'#' as url,fid,px from model where id in "
					+ "(select f.mid from role_function rf ,role_user u,function f where f.id=rf.fid and u.rid = rf.rid and u.uid='"
					+ uid
					+ "') and fid = '"
					+ mid
					+ "' union all "
					+ "select id,name,'f' as lx,url,mid as fid,px from function where id in "
					+ "(select fid from role_function rf ,role_user u where u.rid = rf.rid and u.uid='"
					+ uid + "') and mid = '" + mid
					+ "' )as a  order by px asc ";
		}
		Session session = this.getSession();
		Connection conn;
		try {
			conn = this.getJdbcTemplate().getDataSource().getConnection();

			Statement stm = conn.createStatement();
			ResultSet rs = stm.executeQuery(sql);
			while (rs.next()) {
				Menu mo = new Menu();
				mo.setFid(rs.getString("fid"));
				mo.setName(rs.getString("name"));
				mo.setLx(rs.getString("lx"));
				mo.setUrl(rs.getString("url"));
				mo.setId(rs.getString("id"));
				mo.setPx(rs.getString("px"));
				list.add(mo);
			}
			rs.close();
			stm.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (session != null) {
				releaseSession(session);
			}
		}
		return list;
	}

	/**
	 * 查询条件的封装
	 * 
	 * @param functionForm
	 * @return
	 */
	private StringBuffer getStringBuffer(FunctionForm functionForm,
			StringBuffer buf) {
		/*
		 * 需要加入查询条件时封装
		 */
		buf.append(" where 1=1 ");
		if (StringUtils.isNotBlank(functionForm.getMid())) {
			buf.append(" and t.mid = '" + functionForm.getMid().trim() + "'");
		}
		if (StringUtils.isNotBlank(functionForm.getId())) {
			buf.append(" and t.id = '" + functionForm.getId().trim() + "'");
		}
		return buf;
	}
}
